﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using OddUserManager.Model;
using OddUserManager.Service.IServices;
using OddUserManager.Web.Common;
using OddUserManager.Web.Models;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace OddUserManager.Web.Controllers
{
    public class OddController : BaseController
    {
        IOddService _service;
        IOddUserService _userService;
        IRealTimeJCMatchService _matchService;
        //IRoyaltySettingsService _royaltySettingsService;
        //IFundDispatchService _fundDispatchService;
        //IRebateSettingsService _rebateSettingsService;
        ISiteService _siteService;




        private const string cacheKey = "oddCache";


        public OddController(IOddService service, IOddUserService userService, IRealTimeJCMatchService matchService, ISiteService siteService)
        {
            _service = service;
            _userService = userService;
            _matchService = matchService;
            //_royaltySettingsService = royaltySettingsService;
            //_fundDispatchService = fundDispatchService;
            //_rebateSettingsService = rebateSettingsService;
            _siteService = siteService;

        }

        //public OddController(IOddService service, IOddUserService userService, IRealTimeJCMatchService matchService, IRoyaltySettingsService royaltySettingsService, IFundDispatchService fundDispatchService, IRebateSettingsService rebateSettingsService, ISiteService siteService)
        //{
        //    _service = service;
        //    _userService = userService;
        //    _matchService = matchService;
        //    _royaltySettingsService = royaltySettingsService;
        //    _fundDispatchService = fundDispatchService;
        //    _rebateSettingsService = rebateSettingsService;
        //    _siteService = siteService;

        //}
        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }


        public IActionResult GetSelectedMatchOddDataByMatchIds(List<int> ids)
        {
            JsonData d = new JsonData();
            try
            {
                if (ids == null || ids.Count == 0)
                {
                    d.Data = null;
                }
                else
                {
                    d.Data = _service.GetSelectedMatchOddDataByMatchIds(ids);
                }
            }
            catch (Exception ex)
            {
                d.Message = ex.Message;
                d.Success = false;
            }

            return Json(d);
        }


        public IActionResult DownloadFile(DateTime sTime, DateTime eTime, string dSid)
        {


            var ids = GetSiteIds(int.Parse(dSid));

            var list = _service.GetOddBySiteIdsAndTime(sTime, eTime, ids);
            list = list.OrderBy(p => p.LotteryTime).ThenBy(p => p.CreateTime).ToList();
            StringBuilder sb = new StringBuilder();
            sb.Append("<table border='1' cellspacing='1' cellpadding = '1'><thead>");
            var allUser = _userService.GetAllUserList();
            var sites = _siteService.GetAllList();
            sb.Append("<th>序号</th><th>发单时间</th><th>开奖时间</th><th>站点</th><th>账号</th><th>金额</th><th>奖金</th><th>赔率</th><th>状态</th><th>红包</th><th>跟单</th><th>人数</th><th>操作人</th><th>下单人</th><th>编辑人</th><th>投注内容</th></thead><tbody>");
            if (null != list && list.Count > 0)
            {
                for (var i = 0; i < list.Count; i++)
                {
                    var odd = list[i];
                    sb.Append("<tr>");
                    sb.Append($"<td>{(i + 1)}</td>");
                    sb.Append($"<td>{odd.CreateTime}</td>");
                    sb.Append($"<td>{odd.LotteryTime}</td>");
                    sb.Append($"<td>{sites.FirstOrDefault(p => p.Id == odd.SiteId).Name}</td>");
                    sb.Append($"<td>{odd.CreateOddUserName}</td>");
                    sb.Append($"<td>{odd.OwnPurchaseMoney}</td>");

                    sb.Append($"<td>{odd.OwnBonus}</td>");
                    sb.Append($"<td>{(odd.OwnPurchaseMoney == 0 ? 0 : Math.Round((odd.OwnBonus / odd.OwnPurchaseMoney), 2))}</td>");

                    sb.Append($"<td>{odd.State.ToString()}</td>");
                    sb.Append($"<td>{odd.ProfitAndLoss}</td>");
                    sb.Append($"<td>{odd.DocumentaryMoney}</td>");
                    sb.Append($"<td>{odd.DocumentaryUserCount}</td>");

                    sb.Append($"<td>{odd.AppUserName}</td>");
                    sb.Append($"<td>{odd.ConfirmAppUserName}</td>");
                    sb.Append($"<td>{odd.LastEditAppUserName}</td>");
                    sb.Append($"<td>{GetContentString(odd)}</td>");
                    sb.Append("</tr>");
                }
            }
            sb.Append("</tbody></table>");

            var stream = new MemoryStream();
            var streamWriter = new StreamWriter(stream);
            streamWriter.Write(sb.ToString(), Encoding.UTF8);
            streamWriter.Flush();
            stream.Seek(0, SeekOrigin.Begin);
            return File(stream, "application/octet-stream", "file.xls");
        }


        public string GetContentString(Odd data)
        {
            var ss = "";

            if (null != data.BetDetailOddList && data.BetDetailOddList.Count > 0)
            {

                for (var i = 0; i < data.BetDetailOddList.Count; i++)
                {
                    var n = data.BetDetailOddList[i];
                    var s = "";
                    var pay = 1.0m; var r = "";
                    if (null != n.BetDetailOddContentsList && n.BetDetailOddContentsList.Count > 0)
                    {

                        for (var j = 0; j < n.BetDetailOddContentsList.Count; j++)
                        {
                            var k = n.BetDetailOddContentsList[j];
                            r += ((int)k.LotteryResults) + "";
                            pay = pay * k.SelectedOdds;
                            if (k.FixOdds == "" || Convert.ToInt32(k.FixOdds) == 0)
                            {
                                s += k.WeekName + k.SelectedResult.ToString();

                            }
                            else
                            {
                                s += k.WeekName + "让" + k.FixOdds + k.SelectedResult.ToString().Replace("让", "");

                            }
                            if (k.LotteryResults == LotteryResults.已中奖)
                            {

                                s += "<span class='red'>" + k.SelectedOdds + "</span>";
                            }
                            else if (k.LotteryResults == LotteryResults.未中奖)
                            {
                                s += "<span class='blue'>" + k.SelectedOdds + "</span>";
                            }
                            else
                            {
                                s += k.SelectedOdds;

                            }
                            if (j < n.BetDetailOddContentsList.Count() - 1)
                            {
                                s += '|';
                            }
                        }
                    }

                    if (r == "1" || r == "11" || r == "1-1" || r == "11-1" || r == "111")
                    {
                        ss += n.BetCount + "倍<span class='red'>" + Math.Round(pay, 2) + " </span>" + s;

                    }
                    else if (r == "0" || r == "00" || r == "10" || r == "01" || r == "0-1" || r == "11"
                      || r == "110" || r == "101" || r == "100" || r == "011" || r == "001" || r == "010" || r == "011"
                      || r == "01-1" || r == "00-1" || r == "10-1" || r == "0-1-1"
                  )
                    {
                        ss += n.BetCount + "倍<span class='blue'>" + Math.Round(pay, 2) + " </span>&nbsp;" + s;

                    }
                    else
                    {
                        ss += n.BetCount + "倍" + Math.Round(pay, 2) + "&nbsp; " + s;

                    }


                    ss += ";";
                }



            }
            return ss;
        }

        public IActionResult RedBlackData()
        {
            return View();
        }


        public IActionResult DeleteMuti(string ids)
        {
            JsonData d = new JsonData();
            try
            {
                string[] idArray = ids.Split(',');
                List<int> delIds = new List<int>();
                foreach (string id in idArray)
                {
                    delIds.Add(int.Parse(id));
                }
                _service.DeleteBatchOdd(delIds);


                //foreach (var i in delIds)
                //{
                //    _fundDispatchService.DeleteByOddId(i);
                //}
              
            }
            catch (Exception ex)
            {
                d.Success = false;
                d.Message = ex.Message;
            }
            return Json(d);
        }
        public IActionResult Delete(int id)
        {
            JsonData d = new JsonData();
            try
            {
                _service.DeleteOddById(id);
               
            }
            catch (Exception ex)
            {
                d.Success = false;
                d.Message = ex.Message;
            }
            return Json(d);
        }
        public IActionResult Get(int id)
        {
            JsonData d = new JsonData();
            d.Data = _service.GetOddById(id);
            return Json(d);
        }


        public IActionResult GetAllOdds()
        {
            JsonData d = new JsonData();
            d.Data = CacheData.AllOdds;

            return Json(d);
        }

        [HttpPost]
        public IActionResult GetOddByOddUserId(string oddUserId, int startPage, int pageSize)
        {

            List<Odd> list = null;
            int rowCount = 0;
            int id = 0;
            if (int.TryParse(oddUserId, out id))
            {
                //小于0 代表是转化后的site Id  等于0代表所有 
                if (id < 0)
                {
                    //list = _service.GetAllList().Where(p=>p.SiteId == (id * -1)).OrderByDescending(p => string.IsNullOrEmpty(p.OrderString) ? p.LotteryTime : DateTime.Parse(p.OrderString.Split(' ')[0])).ThenByDescending(p => string.IsNullOrEmpty(p.OrderString) ? 0 : int.Parse(p.OrderString.Split(' ')[1])).ThenBy(p => p.CreateTime).ToList();
                    //rowCount = list.Count;
                    //list = list.Skip((startPage - 1) * pageSize).Take(pageSize).ToList();


                    list = _service.GetOddsBySiteIds(GetSiteIds(id*-1), startPage, pageSize, out rowCount).OrderByDescending(p => string.IsNullOrEmpty(p.OrderString) ? p.LotteryTime : DateTime.Parse(p.OrderString.Split(' ')[0])).ThenByDescending(p => string.IsNullOrEmpty(p.OrderString) ? 0 : int.Parse(p.OrderString.Split(' ')[1])).ThenByDescending(p => p.CreateTime).ToList();

                }
                else if (id == 0)
                {
                    //list = _service.GetAllList().OrderByDescending(p =>

                    //  string.IsNullOrEmpty(p.OrderString) ? p.LotteryTime : DateTime.Parse(p.OrderString.Split(' ')[0])
                    //).ThenByDescending(p => string.IsNullOrEmpty(p.OrderString) ? 0 : int.Parse(p.OrderString.Split(' ')[1])).ThenByDescending(p => p.CreateTime).ToList();

                    //rowCount = list.Count;
                    //list = list.Skip((startPage - 1) * pageSize).Take(pageSize).ToList();

                    list = _service.GetAllList(startPage, pageSize, out rowCount).OrderByDescending(p => string.IsNullOrEmpty(p.OrderString) ? p.LotteryTime : DateTime.Parse(p.OrderString.Split(' ')[0])).ThenByDescending(p => string.IsNullOrEmpty(p.OrderString) ? 0 : int.Parse(p.OrderString.Split(' ')[1])).ThenByDescending(p => p.CreateTime).ToList();
                }
                else
                {
                    var oddUser = _userService.Get(id);
                    if (oddUser.Site.OddOrderType == OddOrderType.最大比赛编号)
                    {

                        list = _service.GetOddsByCreateUserId(id).OrderByDescending(p =>

                          string.IsNullOrEmpty(p.OrderString) ? p.LotteryTime : DateTime.Parse(p.OrderString.Split(' ')[0])
                        ).ThenByDescending(p => string.IsNullOrEmpty(p.OrderString) ? 0 : int.Parse(p.OrderString.Split(' ')[1])).ThenByDescending(p => p.CreateTime).ToList();

                    }
                    else
                    {
                        list = _service.GetOddsByCreateUserId(id).OrderByDescending(p => p.CreateTime).ToList();
                    }
                    rowCount = list.Count; ;
                    list = list.Skip((startPage - 1) * pageSize).Take(pageSize).ToList();
                }
            }
            else
            {
                var sites = _siteService.GetAllList().ToList();
                var sIds = sites.Where(p => p.Type == oddUserId).Select(p => p.Id).ToList();


                list = _service.GetOddsBySiteIds(string.Join(",", sIds), startPage, pageSize, out rowCount).OrderByDescending(p => string.IsNullOrEmpty(p.OrderString) ? p.LotteryTime : DateTime.Parse(p.OrderString.Split(' ')[0])).ThenByDescending(p => string.IsNullOrEmpty(p.OrderString) ? 0 : int.Parse(p.OrderString.Split(' ')[1])).ThenBy(p => p.CreateTime).ToList();


                //list = _service.GetAllList().Where(p=>sIds.Contains(p.SiteId)).OrderByDescending(p =>

                //      string.IsNullOrEmpty(p.OrderString) ? p.LotteryTime : DateTime.Parse(p.OrderString.Split(' ')[0])
                //    ).ThenByDescending(p => string.IsNullOrEmpty(p.OrderString) ? 0 : int.Parse(p.OrderString.Split(' ')[1])).ThenByDescending(p => p.CreateTime).ToList();

                //rowCount = list.Count;
                //list = list.Skip((startPage - 1) * pageSize).Take(pageSize).ToList();


            }

            JsonData data = new JsonData();

            PageViewCollection<Odd> pageList = new PageViewCollection<Odd>();
            pageList.Result = list;
            pageList.TotalCount = rowCount;
            pageList.PageIndex = startPage;
            pageList.PageCount = (int)((rowCount / pageSize) + (rowCount%pageSize>0?1:0));
            pageList.PageSize = pageSize;
            data.Success = true;
            data.Message = "查询成功";
            data.Data = pageList;

            return Json(data);
        }


        [HttpPost]
        public IActionResult GetNewOddByOddUserId(string oddUserId, int[] oddMoneyTypes, int oddState, int startPage, int pageSize)
        {

            List<Odd> list = null;
            int rowCount = 0;
            int id = 0;
            JsonData data = new JsonData();
            if (int.TryParse(oddUserId, out id))
            {
                //小于0 代表是转化后的site Id  等于0代表所有 
                if (id < 0)
                {

                    list = _service.GetOddsBySiteIds(GetSiteIds(id * -1).ToString(), oddMoneyTypes, oddState, startPage, pageSize, out rowCount).OrderByDescending(p => string.IsNullOrEmpty(p.OrderString) ? p.LotteryTime : DateTime.Parse(p.OrderString.Split(' ')[0])).ThenByDescending(p => string.IsNullOrEmpty(p.OrderString) ? 0 : int.Parse(p.OrderString.Split(' ')[1])).ThenByDescending(p => p.CreateTime).ToList();

                }
                else
                {
                    var oddUser = _userService.GetUserById(id);

                    list = _service.GetOddsByCreateUserId(id);

                    if (list != null && list.Count > 0)
                    {
                        if (oddMoneyTypes != null && oddMoneyTypes.Length > 0)
                        {
                            list = list.Where((p) => {
                                var flag1 = false;
                                var flag2 = false;
                                var flag3 = false;
                                for (var i = 0; i < oddMoneyTypes.Length; i++)
                                {
                                    if (oddMoneyTypes[i] == 1)
                                    {
                                        flag1 = p.OwnPurchaseMoney < 1000;
                                    }
                                    else if (oddMoneyTypes[i] == 2)
                                    {
                                        flag2 = p.OwnPurchaseMoney >= 1000 && p.OwnPurchaseMoney < 10000;
                                    }
                                    else if (oddMoneyTypes[i] == 3)
                                    {
                                        flag3 = p.OwnPurchaseMoney >= 10000;
                                    }
                                }

                                if (oddState > 0)
                                {
                                    return (flag1 || flag2 || flag3) && (int)p.State == oddState;
                                }

                                return flag1 || flag2 || flag3;

                            }).ToList();
                        }
                        else
                        {
                            list = list.Where(p => p.OwnPurchaseMoney < 0).ToList();
                        }
                    }

                    if (oddUser.Site.OddOrderType == OddOrderType.最大比赛编号)
                    {
                        list = list.OrderByDescending(p =>
                          string.IsNullOrEmpty(p.OrderString) ? p.LotteryTime : DateTime.Parse(p.OrderString.Split(' ')[0])
                        ).ThenByDescending(p => string.IsNullOrEmpty(p.OrderString) ? 0 : int.Parse(p.OrderString.Split(' ')[1])).ThenByDescending(p => p.CreateTime).ToList();
                    }
                    else
                    {
                        list = list.OrderByDescending(p => p.CreateTime).ToList();
                    }

                    rowCount = list.Count; ;
                    list = list.Skip((startPage - 1) * pageSize).Take(pageSize).ToList();
                }
            }
            else
            {

                data.Success = false;
                data.Message = "查询参数出错";
                return Json(data);
            }

           

            PageViewCollection<Odd> pageList = new PageViewCollection<Odd>();
            pageList.Result = list;
            pageList.TotalCount = rowCount;
            pageList.PageIndex = startPage;
            pageList.PageCount = Math.Ceiling(Convert.ToDecimal(rowCount) / pageSize);
            pageList.PageSize = pageSize;
            data.Success = true;
            data.Message = "查询成功";
            data.Data = pageList;

            return Json(data);
        }



        [HttpPost]
        public async Task<IActionResult> Add(Odd odd)
        {
            JsonData d = new JsonData();
            try
            {
                odd.State = OddState.待上传;
                var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                if (result.Succeeded)
                {
                    var Id = result.Principal.Identity.Name;
                    var user = _userService.Get(odd.CreateOddUserId);
                    odd.AppUserId = int.Parse(Id);
                    odd.LastEditAppUserId = int.Parse(Id);
                    odd.BespeakCutoffTime = odd.CreateTime.AddHours(user.Site.MaxBespeakTime);
                    //odd.DocumentaryCutoffTime = DateTime.Parse("1900-01-01");
                    odd.LotteryTime = odd.LotteryTime.AddHours(2);
                    odd.Result = LotteryResults.未开奖;
                }
                else
                {
                    throw new Exception("登录凭证已失效");
                }
                _service.InsertOrUpdateOdd(odd);
                
            }
            catch (Exception ex)
            {
                d.Success = false;
                d.Message = ex.Message;

            }
            return Json(d);
        }
        [HttpPost]
        public async Task<IActionResult> Edit(Odd odd, bool isTe = false)
        {
            JsonData d = new JsonData();
            try
            {
                var updateOdd = _service.GetOddById(odd.Id);
                CopyOddData(updateOdd, odd);
                //if (updateOdd.State == OddState.待确认 || updateOdd.State == OddState.完成)
                //{
                //    var siteId = updateOdd.SiteId;
                //    var createTime = updateOdd.CreateTime;
                //    var royaltySettings = _royaltySettingsService.GetAllRoyaltySettings().Where(p => p.SiteId == siteId && p.StartTime <= createTime && p.EndTime >= createTime).FirstOrDefault();
                //    if (null != royaltySettings)
                //    {
                //        var calculation = RoyaltyCalculationHelper.GetCalculation(royaltySettings.RoyaltyBase);
                //        calculation.Calculation(ref updateOdd, royaltySettings);
                //    }
                //}
                if (isTe)
                {
                    if (updateOdd.OwnBonus > 0)
                    {
                        updateOdd.Result = LotteryResults.已中奖;
                    }
                    else
                    {
                        updateOdd.Result = LotteryResults.未中奖;
                    }
                }
                var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                int appUserId = 0;
                if (result.Succeeded)
                {
                    appUserId = int.Parse(result.Principal.Identity.Name);
                    updateOdd.LastEditAppUserId = appUserId;
                }
                _service.InsertOrUpdateOdd(updateOdd);

                d.Success = true;

            }
            catch (Exception ex)
            {
                d.Success = false;
                d.Message = ex.Message;

            }
            return Json(d);
        }

        private void CopyOddData(Odd updateOdd, Odd odd)
        {
            updateOdd.CreateTime = odd.CreateTime;
            updateOdd.CreateOddUserId = odd.CreateOddUserId;
            updateOdd.State = odd.State;
            updateOdd.DocumentaryUserCount = odd.DocumentaryUserCount;
            updateOdd.DocumentaryMoney = odd.DocumentaryMoney;
            updateOdd.OwnBonus = odd.OwnBonus;
            updateOdd.Remark = odd.Remark;
            updateOdd.AppUserId = odd.AppUserId;
            updateOdd.ProfitAndLoss = odd.ProfitAndLoss;
            updateOdd.Descption = odd.Descption;
            updateOdd.Title = odd.Title;
            var user = _userService.Get(odd.CreateOddUserId);
            updateOdd.SiteId = user.Site.Id;
            //如果自购奖金大于0，填写的实际提成奖金也大于0，则反算出跟单奖金
            //if (updateOdd.OwnBonus>0 && updateOdd.OwnPurchaseMoney>0 && odd.ActualCommission > 0)
            //{
            //    var commission = _royaltySettingsService.GetRoyaltySettingsBySiteId(user.Site.Id).FirstOrDefault(p=>updateOdd.CreateTime>=p.StartTime && updateOdd.CreateTime<p.EndTime);
            //    if (null != commission)
            //    {
            //        var sp = updateOdd.OwnBonus / updateOdd.OwnPurchaseMoney;
            //        if (sp * 100 >= commission.TriggerCondition)

            //        updateOdd.DocumentaryBonus = odd.ActualCommission * 100 / commission.RoyaltyValue;
            //        if (user.Site.Remark=="2")
            //        {
            //            updateOdd.DocumentaryMoney = updateOdd.DocumentaryBonus / sp;
            //        }
            //    } 
            //}
        }
        public async Task<IActionResult> EditOddContents(Odd dto)
        {
            JsonData d = new JsonData();
            try
            {
                if (dto.Id <= 0)
                {
                    d.Success = false;
                    d.Message = "参数不能为空";
                    return Json(d);
                }
                if (null == dto.BetDetailOddList || dto.BetDetailOddList.Count == 0)
                {
                    var aodd = _service.GetOddById(dto.Id);
                    aodd.BetDetailOddList = null;
                    //aodd.OddSelectedMatchList = null;
                    aodd.DocumentaryCutoffTime = new DateTime(1900, 1, 1);
                    aodd.LotteryTime = new DateTime(1900, 1, 1);
                    aodd.State = OddState.预约;
                    aodd.Divisor = dto.Divisor;
                    aodd.Result = LotteryResults.未开奖;
                    var result1 = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                    if (result1.Succeeded)
                    {
                        var Id = result1.Principal.Identity.Name;
                        aodd.LastEditAppUserId = int.Parse(Id);
                    }
                    _service.InsertOrUpdateOdd(aodd);

                    return Json(new { Result = "Success" });
                }

                var odd = _service.GetOddById(dto.Id);
                odd.Divisor = dto.Divisor;
                odd.BetDetailOddList = dto.BetDetailOddList;
                odd.OddSelectedMatchList = dto.OddSelectedMatchList;
                odd.OwnPurchaseMoney = dto.BetDetailOddList.Sum(p => p.BetCount) * 2;
                odd.Result = LotteryResults.未开奖;
                var BetDetailOddContentsList = new List<BetDetailOddContents>();
                dto.BetDetailOddList.ForEach(p =>
                {
                    if (null != p.BetDetailOddContentsList && p.BetDetailOddContentsList.Count > 0)
                    {
                        BetDetailOddContentsList.AddRange(p.BetDetailOddContentsList);
                    }
                });


                if (BetDetailOddContentsList.Count > 0)
                {
                    var ids = BetDetailOddContentsList.Select(p => p.SelectedMatchId).Distinct().ToList();
                    var matchs = _matchService.GetMatchsByIds(ids);
                    var minTime = matchs.Min(p => p.MatchTime);
                    var maxTime = matchs.Max(p => p.MatchTime);
                    var maxIssue = matchs.Max(p => p.Issue);
                    var number = matchs.Where(p => p.Issue == maxIssue).Max(p => p.MatchNumber).Replace("周", "").Replace("一", "").Replace("二", "").Replace("三", "").Replace("四", "").Replace("五", "").Replace("六", "").Replace("日", "");

                    odd.OrderString = maxIssue + " " + number;
                    if (minTime.Hour >= 0 && minTime.Hour < 9)
                    {
                        odd.DocumentaryCutoffTime = new DateTime(minTime.Year, minTime.Month, minTime.Day, 23, 55, 0).AddDays(-1);
                    }
                    else
                    {
                        odd.DocumentaryCutoffTime = minTime.AddMinutes(-5);
                    }

                    //开奖时间为最晚时间的比赛开赛时间后2小时
                    odd.LotteryTime = maxTime.AddHours(2);
                    odd.State = OddState.已上传;
                }
                else
                {
                    odd.State = OddState.预约;
                }
                var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                var appUserId = 0;
                if (result.Succeeded)
                {
                    appUserId = int.Parse(result.Principal.Identity.Name);
                    odd.LastEditAppUserId = appUserId;
                }
                _service.InsertOrUpdateOdd(odd);
               
            }
            catch (Exception ex)
            {
                d.Success = false;
                d.Message = ex.Message;
            }
            return Json(d);
        }

        private string GetSiteIds(int siteId)
        {
            if (siteId < 1) return null;
            List<Site> list = _siteService.GetAllList().ToList();

            Dictionary<int, Dictionary<int, int>> d = new Dictionary<int, Dictionary<int, int>>();
            foreach (Site site in list)
            {
                if (site.ParentId > -1)
                {
                    if (d.ContainsKey(site.ParentId))
                    {
                        var dd = d[site.ParentId];
                        if (!dd.ContainsKey(site.Id))
                        {
                            dd[site.Id] = -1;
                        }
                    }
                    else
                    {
                        Dictionary<int, int> dd = new Dictionary<int, int>();
                        dd[site.Id] = -1;
                        d[site.ParentId] = dd;
                    }
                }
            }

            List<int> siteList = new List<int>();
            GetTreeNode(d, siteList, siteId);

            return string.Join(",", siteList);
        }

        private void GetTreeNode(Dictionary<int, Dictionary<int, int>> d, List<int> list, int id)
        {
            list.Add(id);
            if (!d.ContainsKey(id)) return;
            Dictionary<int, int> dd = d[id];
            foreach (int key in dd.Keys)
            {
                GetTreeNode(d, list, key);
            }

        }

        public async Task<IActionResult> UpdateCertification(int oddId)
        {
            var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            var appUserId = 0;
            if (result.Succeeded)
            {
                appUserId = int.Parse(result.Principal.Identity.Name);
                _service.UpdateCertification(oddId, true, appUserId);
            }
            return Json(new { Success = true, Message = "更新成功" });
        }


       


        [HttpPost]
        public IActionResult GetOddBySelectedMatchIds(List<int> ids) {
            var list = _service.GetOddBySelectedMatchIds(ids);
            JsonData d = new JsonData();
            d.Data = list;
            return Json(d);
        }
    }
}
